var recordBtn = document.querySelector("button#record")
var playBtn =  document.querySelector("button#play")
var downloadBtn =  document.querySelector("button#download")
var divConstraints = document.querySelector("div#divConstraints")
var videoObj = document.querySelector("video#videoId")
var playVideoObj = document.querySelector("video#playVideoId")

var buffer = null
var mediaRecorder = null

function getMediaStream(stream) {
    var videoTrack = stream.getVideoTracks()[0]
    var videoConstraints = videoTrack.getSettings()
    divConstraints.textContent = JSON.stringify(videoConstraints,null,2)

    window.stream = stream
    videoObj.srcObject = stream

    return navigator.mediaDevices.enumerateDevices()
}

function handleDataAvailable(e) {
    if (e && e.data && e.data.size > 0) {
        buffer.push(e.data)
    }
}

/**********************采集用户的摄像头和麦克风************************** */
/**
function handleError(err){
	console.log('getUserMedia error:', err);
}

function start(){
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.log('getUserMedia is not supported!')
        return
    }

    var deviceId = videoObj.value; 
    const constraints = {
        video: {
            width: 320,
            height: 240,
            frameRate: 15,
            facingMode: 'enviroment',
            deviceId : deviceId ? {exact:deviceId} : undefined
        },
        audio: true
    }

    navigator.mediaDevices.getUserMedia(constraints).then(getMediaStream).catch(handleError)
}

start()
 */

/**********************采集桌面************************** */
function handleError(err){
	console.log('getDisplayMedia error:', err);
}

function start(){
    if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
        console.log('getDisplayMedia is not supported!')
        return
    }

    const constraints = {
        video: true,
        audio: true
    }

    navigator.mediaDevices.getDisplayMedia(constraints).then(getMediaStream).catch(handleError)
}

start()

// videoObj.onchange = start

function startRecord() {
    buffer = []

    var options = {
        mimeType: 'video/webm;codecs=vp8'
    }

    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
        console.log(`${options.mimeType} is not supported!`)
        return
    }

    try {
        mediaRecorder = new MediaRecorder(window.stream,options)
    } catch (error) {
        console.error('Failed to create MediaRecorder:',error)
        return
    }

    mediaRecorder.ondataavailable = handleDataAvailable
    mediaRecorder.start(10)
}

function stopRecord() {
    mediaRecorder.stop()
}

recordBtn.onclick = () => {
    if (recordBtn.textContent === 'Start Record') {
        startRecord()
        recordBtn.textContent = 'Stop Record'
        downloadBtn.disabled = true
    } else {
        stopRecord()
         recordBtn.textContent = 'Start Record'
        downloadBtn.disabled = false
    }
}

playBtn.onclick = () => {
    var blob = new Blob(buffer,{type: 'video/webm'})
    playVideoObj.src = window.URL.createObjectURL(blob)
    playVideoObj.srcObject = null
    playVideoObj.contains = true
    playVideoObj.play()
}

downloadBtn.onclick = () => {
    var blob = new Blob(buffer,{type: 'video/webm'})
    var url = window.URL.createObjectURL(blob)
    var a = document.createElement('a')

    a.href = url
    a.style.display = 'none'
    a.download = 'aaa.webm'
    a.click()
}